<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.slider-wrap{
				position: relative;
				width: 400px;
				height: 20px;
				background:#eee;
			}
			.slider-wrap2{
				
				width: 20px;
				height: 400px;
				
			}
			.slider-bar{
				position: absolute;
				width: 50px;
				height: 20px;
				background: #ccc;
			}
			.slider-bar2{
				
				width: 20px;
				height: 50px;
				background: #ccc;
			}
		</style>
	</head>
	<body>
		<div class="slider-wrap">
			<div class="slider-bar slider-bar1"></div>
		</div>
		
		<div class="slider-wrap slider-wrap2">
			<div class="slider-bar slider-bar2"></div>
		</div>
		<script type="text/javascript">
			
			slider({el:'.slider-bar1',dir:'x',max:350,min:0,val:20}),
			slider({el:'.slider-bar2',dir:'y',max:350,min:0,val:100})
			function slider(params){
				var {el,dir,max,min,val} = params
				val=val?val:0
				var sliderBar = document.querySelector(params.el)
				sliderBar.style[dir==='x'?'left':'top']=val+'px'
				var orgX=0;
				var orgY=0;
				
				sliderBar.addEventListener('mousedown',function(e){
					var e = e||window.event
					orgX=e.clientX-sliderBar.offsetLeft
					orgY=e.clientY-sliderBar.offsetTop
					e.preventDefault()
					document.addEventListener('mousemove',touchMove)
					document.addEventListener('mouseup',touchEnd)
					return false
				})
				function touchMove(e){
					var e = e||window.event
					// 判断方向
					if(dir==='x'){
						val=e.clientX-orgX
					}else if(dir==='y'){
						val=e.clientY-orgY
					}
					// 判断最大最小值  范围限定
					if(val<min){
						val=min
					}else if(val>max){
						val=max
					}

					sliderBar.style[dir==='x'?'left':'top']=val+'px'
					
				}
				function touchEnd(e){
					document.removeEventListener('mousemove',touchMove)
					document.removeEventListener('mouseup',touchEnd)
				}
			}
			
		</script>
	</body>
</html>
